<?php

namespace Service\AppService;

use Service\BaseService;

class SkuCodeBuilderService extends BaseService
{
    public $uniqueStr = null;

    /**
     * 获取系统生成产生的skuCode
     */
    public function getCode():string
    {
        $uniqueStr = $this->getUniqueStr();

        //如果毫秒数相同，则休眠一毫秒之后
        if( $this->uniqueStr == $uniqueStr )
        {
            usleep(1000);
            $uniqueStr = $this->getUniqueStr();
        }

        //赋值当前skuCode
        $this->uniqueStr = $uniqueStr;
        return $uniqueStr;
    }

    /**
     * 获取毫秒级别的日期字符串
     * @return string
     */
    protected function getUniqueStr(): string
    {
        list($time,$mics) = explode(".",microtime(true));
        $length = strlen($mics);
        $pos = [
            '1' => '000',
            '2' => '00',
            '3' => '0'
        ];
        $mics = isset($pos[$length]) ? $mics.$pos[$length] : $mics;
        return date('ymdHis').$mics;
    }

}